package com.gitee.simons.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gitee.simons.common.exception.ServiceException;
import com.gitee.simons.common.utils.MD5Util;
import com.gitee.simons.system.entity.po.SysUser;
import com.gitee.simons.system.entity.po.SysUserRole;
import com.gitee.simons.system.mapper.SysUserMapper;
import com.gitee.simons.system.mapper.SysUserRoleMapper;
import com.gitee.simons.system.service.SysUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author simons
 * @since 2020-07-07
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insert(SysUser sysUser, List<String> roleIds) {

        if (sysUser == null) {
            throw new ServiceException("注册信息不能为空");
        }
        String password = sysUser.getPassword();
        if(StringUtils.isBlank(password)) {
            throw new ServiceException("密码不能为空");
        }

        sysUser.setPassword(MD5Util.getMD5Str(password));
        // 用户信息处理
        this.save(sysUser);
        // 用户角色信息处理
        this.dealUserRole(sysUser.getId(), roleIds);

    }

    @Override
    public void updateUser(SysUser sysUser) {
        if (sysUser == null) {
            throw new ServiceException("注册信息不能为空");
        }
        // 用户信息处理
        this.saveOrUpdate(sysUser);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(SysUser sysUser, List<String> roleIds) {
        this.updateUser(sysUser);
        // 用户角色信息处理
        this.dealUserRole(sysUser.getId(), roleIds);
    }

    private void dealUserRole(String userId, List<String> roleIds) {
        // 删除旧的用户角色信息
        sysUserRoleMapper.delete(new UpdateWrapper<SysUserRole>().lambda().eq(SysUserRole::getUserId, userId));

        // 全量插入用户角色信息
        for (String roleId : roleIds) {
            if(StringUtils.isBlank(roleId)) {
                log.warn("新增或修改用户-角色信息，当前角色id为空，直接跳过");
                continue;
            }
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setRoleId(roleId);
            sysUserRole.setUserId(userId);
            sysUserRoleMapper.insert(sysUserRole);
        }
    }
}
